#!/bin/sh
### BEGIN INIT INFO
# Provides:          myapp          		# 服务名（必须唯一）
# Required-Start:    $remote_fs $syslog  	# 启动依赖（文件系统、日志服务）
# Required-Stop:     $remote_fs $syslog   	# 停止依赖
Default-Start:       2 3       			# 开机运行级别（2-5 为多用户图形/命令行模式）
# Default-Stop:      0 1 6          		# 关机/重启级别（0=关机，1=单用户，6=重启）
# Short-Description: Start/stop my custom app  	# 简短描述
# Description:       Auto-start myapp on boot and manage it  # 详细描述
### END INIT INFO

# 配置变量（根据实际修改）
APP_PATH="/home/rpdzkj/pack/usr/bin/applepure"  	# 程序路径
LOG_PATH="/home/rpdzkj/pack/log.txt"    					# 日志路径
PID_FILE="/home/rpdzkj/pack/applepure.pid"    				# PID文件（用于判断程序是否运行）
WORK_DIR="/home/rpdzkj/pack"

# 启动函数
start() {
    if [ -f "$PID_FILE" ] && kill -0 $(cat "$PID_FILE") 2>/dev/null; then
        echo "lepure is already running..."
        return 0
    fi
    echo "Starting lepure..."
    
    export QT_QPA_PLATFORM=eglfs
    export QT_QPA_EGLFS_KMS_CONFIG=/etc/eglfs.json
    cd "$WORK_DIR" || { echo "Failed to enter work dir $WORK_DIR"; exit 1; }   

    # 后台运行程序，将输出重定向到日志，记录PID到文件
    nohup "$APP_PATH" >> "$LOG_PATH" 2>&1 &
    echo $! > "$PID_FILE"
    echo "lepure started successfully."
}

# 停止函数
stop() {
    if [ ! -f "$PID_FILE" ] || ! kill -0 $(cat "$PID_FILE") 2>/dev/null; then
        echo "lepure is not running..."
        return 0
    fi
    echo "Stopping lepure..."
    # 杀死进程，删除PID文件
    kill $(cat "$PID_FILE")
    rm -f "$PID_FILE"
    echo "lepure stopped successfully."
}

# 重启函数
restart() {
    stop
    sleep 2  # 等待进程完全停止
    start
}

# 状态查询函数
status() {
    if [ -f "$PID_FILE" ] && kill -0 $(cat "$PID_FILE") 2>/dev/null; then
        echo "myapp is running (PID: $(cat "$PID_FILE"))"
    else
        echo "myapp is not running"
        rm -f "$PID_FILE"  # 清理无效PID文件
    fi
}

# 接收命令参数（start/stop/restart/status）
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    status)
        status
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
        ;;
esac

exit 0
